ChatFrame1:AddMessage("\124cFF1987FFHex\124cFFFFFFFFChat Loaded.")

CHAT_FRAME_TAB_SELECTED_MOUSEOVER_ALPHA = 1.0
CHAT_FRAME_TAB_SELECTED_NOMOUSE_ALPHA = 0    
CHAT_FRAME_TAB_NORMAL_MOUSEOVER_ALPHA = 3.0
CHAT_FRAME_TAB_NORMAL_NOMOUSE_ALPHA = 0    
CHAT_FRAME_FADE_OUT_TIME = 0.5
CHAT_FRAME_FADE_TIME = 0.10

    function spamm(self, event, arg1)
        if strfind(arg1, "You have unlearned") or strfind(arg1,"You have learned a new spell:") or strfind(arg1, "You have learned a new ability:") or strfind(arg1, "Your pet has unlearned") then
           return true
        end
            if strfind(arg1, "Welcome to World of Warcraft!") or strfind(arg1,"We care about player security and encourage you to") or strfind(arg1, "visit http://eu.battle.net/security/ for helpful information") or strfind(arg1, "and tips.") then
                return true
            end
        end

	ChatFrame_AddMessageEventFilter("CHAT_MSG_SYSTEM", spamm)

CHAT_FONT_HEIGHTS = {8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

CHAT_FLAG_AFK = '[AFK] '
CHAT_FLAG_DND = '[DND] '
CHAT_FLAG_GM = '[GM] '

CHAT_YOU_CHANGED_NOTICE = '|Hchannel:%d|h[%s]|h'

CHAT_SAY_GET = '%s:\32'
CHAT_YELL_GET = '%s:\32'

CHAT_WHISPER_GET = 'f - %s:\32'
CHAT_WHISPER_INFORM_GET = 't - %s:\32'

CHAT_GUILD_GET = 'g - %s:\32'
CHAT_OFFICER_GET = 'Officer - %s:\32'

CHAT_PARTY_GUIDE_GET  = 'dg - %s:\32' 
CHAT_PARTY_GET = 'p - %s:\32'
CHAT_PARTY_LEADER_GET = 'pl - %s:\32'

CHAT_MONSTER_PARTY_GET = '[|Hchannel:raid|hR|h] %s:\32'

CHAT_RAID_GET = 'r - %s:\32'
CHAT_RAID_WARNING_GET = 'rw - %s:\32'
CHAT_RAID_LEADER_GET = 'rl - %s:\32'

CHAT_BATTLEGROUND_GET = 'bg - %s:\32'
CHAT_BATTLEGROUND_LEADER_GET = 'bgl - %s:\32'

CHAT_YOU_CHANGED_NOTICE = '# |Hchannel:%d|h%s|h'
CHAT_YOU_JOINED_NOTICE = '+ |Hchannel:%d|h%s|h'
CHAT_YOU_LEFT_NOTICE = '- |Hchannel:%d|h%s|h'

BN_INLINE_TOAST_FRIEND_OFFLINE = '%s has gone |cffff0000offline|r'
BN_INLINE_TOAST_FRIEND_ONLINE = '%s has come |cff00ff00online|r'

CHAT_BN_WHISPER_GET = 'From |cff1eff00%s:\32|r'
CHAT_BN_WHISPER_INFORM_GET = 'To |cff1eff00%s:\32|r'

ERR_FRIEND_OFFLINE_S = '%s has gone |cffff0000offline|r'
ERR_FRIEND_ONLINE_SS = '|Hplayer:%s|h[%s]|h has come |cff00ff00online|r'

ChatTypeInfo['BN_WHISPER'].sticky = 1
ChatTypeInfo['CHANNEL'].sticky = 1
ChatTypeInfo['GUILD'].sticky = 1
ChatTypeInfo['OFFICER'].sticky = 1
ChatTypeInfo['PARTY'].sticky = 1																	
ChatTypeInfo['RAID'].sticky = 1
ChatTypeInfo['BATTLEGROUND'].sticky = 1
ChatTypeInfo['BATTLEGROUND_LEADER'].sticky = 1

local AddMessage = ChatFrame1.AddMessage    
  
function FCF_AddMessage(self, text, ...)
    if (type(text) == 'string') then
        text = text:gsub('(|HBNplayer.-|h)%[(.-)%]|h', '%1%2|h')
        text = text:gsub('(|Hplayer.-|h)%[(.-)%]|h', '%1%2|h')
        text = text:gsub('%[(%d+)%. (.+)%].+(|Hplayer.+)', '[|Hchannel:channel|h%1|h] %3')
        text = format('%s %s', date'|cff707070[%H:%M]|r', text) 		
    end
    return AddMessage(self, text, ...)
end

for i = 1, 7 do
    CreateBorder(_G["ChatFrame"..i], 12, 5, 5, 5, 5, 5, 5, 5, 5, 8, 5, 8)
end

for i = 1, NUM_CHAT_WINDOWS do
    _G['ChatFrame'..i..'EditBox']:SetAltArrowKeyMode(false)
    _G['ChatFrame'..i..'EditBox']:ClearAllPoints()
    _G['ChatFrame'..i..'EditBox']:SetPoint('BOTTOMLEFT', ChatFrame1, 'BOTTOMLEFT', 0, -36)
    _G['ChatFrame'..i..'EditBox']:SetPoint('BOTTOMRIGHT', ChatFrame1, 'BOTTOMRIGHT', 0, -36)
    _G['ChatFrame'..i..'EditBox']:SetBackdrop({
        bgFile = 'Interface\\Buttons\\WHITE8x8',
        insets = {left = 3, right = 3, top = 2, bottom = 2},
    })
    _G['ChatFrame'..i..'EditBox']:SetBackdropColor(0, 0, 0, 0.7)
	_G['ChatFrame'..i..'EditBox']:SetFont('Fonts\\ARIALN.ttf', AftermathhUI.config.editboxfontsize, 'THINOUTLINE')
    _G['ChatFrame'..i..'EditBoxHeader']:SetFont('Fonts\\ARIALN.ttf', AftermathhUI.config.editboxheaderfontsize, 'THINOUTLINE')
    
    for k = 6, 11 do
        select(k, _G['ChatFrame'..i..'EditBox']:GetRegions()):SetTexture(nil)
    end
    
    CreateBorder(_G['ChatFrame'..i..'EditBox'], 11, 1, 1, 1, -2, -1, -2, -1, -2, -1, -2, -1)
end
    
hooksecurefunc('FCFTab_UpdateColors', function(self, selected)
    local playerColor = RAID_CLASS_COLORS[select(2, UnitClass('player'))]
	if (selected) then
		self:GetFontString():SetTextColor(playerColor.r, playerColor.g, playerColor.b)
	else
		self:GetFontString():SetTextColor(playerColor.r, playerColor.g, playerColor.b)
	end
end)

hooksecurefunc('FloatingChatFrame_OnMouseScroll', function(self, direction)
    if (direction > 0) then
        if (IsShiftKeyDown()) then
            self:ScrollToTop()
        else
            self:ScrollUp()
            self:ScrollUp()
        end
    elseif (direction < 0)  then
        if (IsShiftKeyDown()) then
            self:ScrollToBottom()
        else
            self:ScrollDown()
            self:ScrollDown()
        end
    end
end)  
    
function SkinTab(self)
    local chat = _G[self]
    local tab = _G[self..'Tab']
    local tabLeft = _G[self..'TabLeft']
    local tabMiddle = _G[self..'TabMiddle']
    local tabRight = _G[self..'TabRight']
    local tabText = _G[self..'TabText']
    local tabSelLeft = _G[self..'TabSelectedLeft']
    local tabSelMiddle = _G[self..'TabSelectedMiddle']
    local tabSelRight = _G[self..'TabSelectedRight']
    local tabHigLeft = _G[self..'TabHighlightLeft']
    local tabHigRight = _G[self..'TabHighlightRight']
    local tabHigMiddle = _G[self..'TabHighlightMiddle']
	local a1, a2, a3, a4, a5 = tabText:GetPoint()
	
    tabHigMiddle:SetTexture(nil)
	tabHigRight:SetTexture(nil)
	tabHigLeft:SetTexture(nil)
	tabSelRight:SetTexture(nil)
	tabSelMiddle:SetTexture(nil)
	tabSelLeft:SetTexture(nil)
	tabRight:SetTexture(nil)
	tabMiddle:SetTexture(nil)
	tabLeft:SetTexture(nil)

	tabText:SetPoint(a1, a2, a3, a4, a5 + 3, tab)
	tabText:SetFont('Fonts\\ARIALN.ttf', AftermathhUI.config.chattabfontsize, 'THINOUTLINE') 
    tabText:SetJustifyH('CENTER')
    tabText:SetWidth(500)
	tab:SetFrameStrata('BACKGROUND')
    CreateBorder(tab, 12, 6, 6, 6, -3, -4, -3, -4, -3, 1, -3, 1)
	tab:SetBackdrop({
	    bgFile = 'Interface\\Buttons\\WHITE8x8',
		insets = {left = 5, right = 5, top = 5, bottom = 2},
	})
	tab:SetBackdropColor(0, 0, 0, 0.75)
end  

local function ModChat(self)
    local chat = _G[self]
	local font, size = chat:GetFont()
	local buttonDown = _G[self..'ButtonFrameDownButton']
	local buttonUp = _G[self..'ButtonFrameUpButton']
	local buttonBottom = _G[self..'ButtonFrameBottomButton']
	
    chat:SetClampedToScreen(false)
	chat:SetFrameStrata('HIGH')
    chat:SetClampRectInsets(0, 0, 0, 0)
    chat:SetMaxResize(UIParent:GetWidth(), UIParent:GetHeight())
    chat:SetMinResize(150, 25)
    chat:SetFont(font, size, 'THINOUTLINE')
	chat:SetShadowOffset(0, 0)
    chat:SetShadowColor(0, 0, 0, 0)
	chat:SetBackdrop({
		bgFile = 'Interface\\Buttons\\WHITE8x8',
        insets = {top = -3, left = -5, bottom = -5, right = -5},
	})
	chat:SetBackdropColor(0, 0, 0, 0.75)
	
    buttonUp:SetAlpha(0)
    buttonUp:EnableMouse(false)
   
    buttonDown:SetAlpha(0)
    buttonDown:EnableMouse(false)
	
    buttonBottom:SetAlpha(0)
    buttonBottom:EnableMouse(false)
	
	FriendsMicroButton:SetAlpha(0)
    FriendsMicroButton:EnableMouse(false)
    FriendsMicroButton:UnregisterAllEvents()

    ChatFrameMenuButton:SetAlpha(0)
    ChatFrameMenuButton:EnableMouse(false)
	
	if (i ~= 2) then
        chat.AddMessage = FCF_AddMessage
    end

    for _, texture in pairs({
        'ButtonFrameBackground',
        'ButtonFrameTopLeftTexture',
        'ButtonFrameBottomLeftTexture',
        'ButtonFrameTopRightTexture',
        'ButtonFrameBottomRightTexture',
        'ButtonFrameLeftTexture',
        'ButtonFrameRightTexture',
        'ButtonFrameBottomTexture',
        'ButtonFrameTopTexture',
    }) do
		_G[self..texture]:SetTexture(nil)
	end
    
    chat.hasModification = true
end
    
local NEW_NUM_CHAT_WINDOWS = NUM_CHAT_WINDOWS + 1

hooksecurefunc('FCF_OpenTemporaryWindow', function()
	local chatFrame, chatTab, conversationIcon
	for _, chatFrameName in pairs(CHAT_FRAMES) do
		local frame = _G[chatFrameName]
		if (frame.isTemporary) then
			if (not frame.inUse and not frame.isDocked) then
				chatFrame = frame
				break
			end
		end
	end

	if (not chatFrame) then
		NEW_NUM_CHAT_WINDOWS = NEW_NUM_CHAT_WINDOWS + 1	
	end
end)
    
hooksecurefunc('FCF_OpenTemporaryWindow', function()
    for i = NUM_CHAT_WINDOWS, NEW_NUM_CHAT_WINDOWS do
        if (_G['ChatFrame'..i]) then
            if (_G['ChatFrame'..i]:IsShown()) then
                if (not _G['ChatFrame'..i].hasModification) then
                    ModChat('ChatFrame'..i)
					CreateBorder(_G['ChatFrame'..i], 12, 5, 5, 5, 5, 5, 5, 5, 5, 8, 5, 8)
                end
                
                if (not _G['ChatFrame'..i].hasSkinnedTabs) then
                    SkinTab('ChatFrame'..i)
					CreateBorder(_G['ChatFrame'..i], 12, 5, 5, 5, 5, 5, 5, 5, 5, 8, 5, 8)
                end
            
                local convButton = _G['ChatFrame'..i..'ConversationButton']
                if (convButton) then
                    convButton:SetAlpha(0)
                    convButton:EnableMouse(false)
                end
            end
        end
    end
    for i = NUM_CHAT_WINDOWS, NEW_NUM_CHAT_WINDOWS do
        local chat = _G['ChatFrame'..i]

        local chatMinimize = _G['ChatFrame'..i..'ButtonFrameMinimizeButton']
        if (chatMinimize) then
            chatMinimize:SetAlpha(0)
            chatMinimize:EnableMouse(0)
        end
    end
end)
    
for i = 1, NUM_CHAT_WINDOWS do
    ModChat('ChatFrame'..i)
    SkinTab('ChatFrame'..i)
end
    
for i = 2, NUM_CHAT_WINDOWS do
    local chat = _G['ChatFrame'..i]
    local chatMinimize = _G['ChatFrame'..i..'ButtonFrameMinimizeButton']
    chatMinimize:SetAlpha(0)
    chatMinimize:EnableMouse(0)
end

local f = CreateFrame('Frame')
f:RegisterEvent('ADDON_LOADED')
f:SetScript('OnEvent', function(_, event)
    if (event == 'ADDON_LOADED' and arg1 == 'Blizzard_GMChatUI') then
        GMChatFrame:EnableMouseWheel(true)
        GMChatFrame:SetScript('OnMouseWheel', ChatFrame1:GetScript('OnMouseWheel'))
        GMChatFrame:SetHeight(200)
        
        GMChatFrameUpButton:SetAlpha(0)
        GMChatFrameUpButton:EnableMouse(false)
        
        GMChatFrameDownButton:SetAlpha(0)
        GMChatFrameDownButton:EnableMouse(false)
        
        GMChatFrameBottomButton:SetAlpha(0)
        GMChatFrameBottomButton:EnableMouse(false)
    end
end)

CreateBorder(BNToastFrame, 12, 1, 1, 1)
BNToastFrame:SetBackdrop({
    bgFile = 'Interface\\Buttons\\WHITE8x8',
})
BNToastFrame:SetBackdropColor(0, 0, 0, 0.75)
BNToastFrameCloseButton:Hide()

BNToastFrame:HookScript('OnShow', function()
    BNToastFrame:ClearAllPoints()
    BNToastFrame:SetPoint('TOPLEFT', UIParent, 5, -5)
end)

local SetItemRef_orig = SetItemRef
function ReURL_SetItemRef(link, text, button, chatFrame)
	if (strsub(link, 1, 3) == "url") then
		local ChatFrameEditBox = ChatEdit_ChooseBoxForSend()
		local url = strsub(link, 5);
		if (not ChatFrameEditBox:IsShown()) then
			ChatEdit_ActivateChat(ChatFrameEditBox)
		end
		ChatFrameEditBox:Insert(url)
		ChatFrameEditBox:HighlightText()

	else
		SetItemRef_orig(link, text, button, chatFrame)
	end
end
SetItemRef = ReURL_SetItemRef

function ReURL_AddLinkSyntax(chatstring)
	if (type(chatstring) == "string") then
		local extraspace;
		if (not strfind(chatstring, "^ ")) then
			extraspace = true;
			chatstring = " "..chatstring;
		end
		chatstring = gsub (chatstring, " www%.([_A-Za-z0-9-]+)%.(%S+)%s?", ReURL_Link("www.%1.%2"))
		chatstring = gsub (chatstring, " (%a+)://(%S+)%s?", ReURL_Link("%1://%2"))
		chatstring = gsub (chatstring, " ([_A-Za-z0-9-%.]+)@([_A-Za-z0-9-]+)(%.+)([_A-Za-z0-9-%.]+)%s?", ReURL_Link("%1@%2%3%4"))
		chatstring = gsub (chatstring, " (%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?):(%d%d?%d?%d?%d?)%s?", ReURL_Link("%1.%2.%3.%4:%5"))
		chatstring = gsub (chatstring, " (%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%s?", ReURL_Link("%1.%2.%3.%4"))
		if (extraspace) then
			chatstring = strsub(chatstring, 2);
		end
	end
	return chatstring
end

REURL_COLOR = "99CCFF"
ReURL_Brackets = false
ReUR_CustomColor = true

function ReURL_Link(url)
	if (ReUR_CustomColor) then
		if (ReURL_Brackets) then
			url = " |cff"..REURL_COLOR.."|Hurl:"..url.."|h["..url.."]|h|r "
		else
			url = " |cff"..REURL_COLOR.."|Hurl:"..url.."|h"..url.."|h|r "
		end
	else
		if (ReURL_Brackets) then
			url = " |Hurl:"..url.."|h["..url.."]|h "
		else
			url = " |Hurl:"..url.."|h"..url.."|h "
		end
	end
	return url
end

for i=1, NUM_CHAT_WINDOWS do
	local frame = getglobal("ChatFrame"..i)
	local addmessage = frame.AddMessage
	frame.AddMessage = function(self, text, ...) addmessage(self, ReURL_AddLinkSyntax(text), ...) end
end

local CopyChat = CreateFrame('Frame', 'nChatCopy', UIParent)
CopyChat:SetWidth(500)
CopyChat:SetHeight(400)
CopyChat:SetPoint('LEFT', UIParent, 'LEFT', 3, 10)
CopyChat:SetFrameStrata('DIALOG')
CopyChat:Hide()
CopyChat:SetBackdrop({
	bgFile = [[Interface\Buttons\WHITE8x8]],
	insets = {left = 3, right = 3, top = 4, bottom = 3
}})
CopyChat:SetBackdropColor(0, 0, 0, 0.7)

CreateBorder(CopyChat, 12, 1, 1, 1)

CopyChatBox = CreateFrame('EditBox', 'nChatCopyBox', CopyChat)
CopyChatBox:SetMultiLine(true)
CopyChatBox:SetAutoFocus(true)
CopyChatBox:EnableMouse(true)
CopyChatBox:SetMaxLetters(99999)
CopyChatBox:SetFont('Fonts\\ARIALN.ttf', 13, 'THINOUTLINE')
CopyChatBox:SetWidth(590)
CopyChatBox:SetHeight(590)
CopyChatBox:SetScript('OnEscapePressed', function() CopyChat:Hide() end)

local Scroll = CreateFrame('ScrollFrame', 'nChatCopyScroll', CopyChat, 'UIPanelScrollFrameTemplate')
Scroll:SetPoint('TOPLEFT', CopyChat, 'TOPLEFT', 8, -30)
Scroll:SetPoint('BOTTOMRIGHT', CopyChat, 'BOTTOMRIGHT', -30, 8)
Scroll:SetScrollChild(CopyChatBox)

local lines = {}
local getLines = function(...)
	local count = 1

	for i = select('#', ...), 1, -1 do
		local region = select(i, ...)
		
		if region:GetObjectType() == 'FontString' then
			lines[count] = tostring(region:GetText())
			count = count + 1
		end
	end

	return count - 1
end

local copyChat = function(self, chatTab)
	local chatFrame = _G['ChatFrame' .. chatTab:GetID()]
	local _, fontSize = chatFrame:GetFont()
	
	FCF_SetChatWindowFontSize(chatFrame, chatFrame, 0.01)
	
	local lineCount = getLines(chatFrame:GetRegions())
	
	FCF_SetChatWindowFontSize(chatFrame, chatFrame, fontSize)

	if lineCount > 0 then
		local text = table.concat(lines, '\n', 1, lineCount)

		CopyChat:Show()
		CopyChatBox:SetText(text)
	end
end

local info = {
	text = 'Copy Off Chat',
	func = copyChat,
	notCheckable = 1	
}

local origFCF_Tab_OnClick = _G.FCF_Tab_OnClick
local FCF_Tab_OnClickHook = function(chatTab, ...)
	origFCF_Tab_OnClick(chatTab, ...)

	info.arg1 = chatTab
	
	UIDropDownMenu_AddButton(info)
end

FCF_Tab_OnClick = FCF_Tab_OnClickHook

local events = {
 CHAT_MSG_SAY = "chatBubbles",
 CHAT_MSG_YELL = "chatBubbles",
 CHAT_MSG_PARTY = "chatBubblesParty",
 CHAT_MSG_PARTY_LEADER = "chatBubblesParty",
 CHAT_MSG_MONSTER_SAY = "chatBubbles",
 CHAT_MSG_MONSTER_YELL = "chatBubbles",
 CHAT_MSG_MONSTER_PARTY = "chatBubblesParty",
}

local function SkinFrame(frame)
	for i=1, frame:GetNumRegions() do
		local region = select(i, frame:GetRegions())
		if region:GetObjectType() == 'Texture' then
			region:SetTexture(nil)
		elseif region:GetObjectType() == 'FontString' then
			frame.text = region
		end
	end
    frame.text:SetFont('Fonts\\ARIALN.ttf', 14, "THINOUTLINE")
    frame.text:SetJustifyH("LEFT")
	frame.text:SetNonSpaceWrap(true)
	frame.text:SetWidth(120)
   
    frame.sender = frame:CreateFontString()
    frame.sender:SetPoint("TOP", 0, -10)
    frame.sender:SetPoint("LEFT", frame.text)
    frame.sender:SetPoint("RIGHT", frame.text)
    frame.sender:SetFont('Fonts\\ARIALN.ttf', 12, "THINOUTLINE")
    frame.sender:SetJustifyH("LEFT")
	frame.sender:SetNonSpaceWrap(true)
	frame.sender:SetWidth(70)

    frame:ClearAllPoints()
    frame:SetPoint("TOPLEFT", frame.text, -10, 25)
    frame:SetPoint("BOTTOMRIGHT", frame.text, 10, -10)
	frame:SetBackdrop({
        bgFile = [[Interface\Buttons\WHITE8x8]],
		insets = {top = 1, left = 1, bottom = 1, right = 1},
	})
	frame:SetBackdropColor(0, 0, 0, .5)
    
	CreateBorder(frame, 12, 1, 1, 1)
	
    frame:HookScript("OnHide", function() frame.inUse = false end)
end

local function UpdateFrame(frame, guid, name)
	if not frame.text then SkinFrame(frame) end
	frame.inUse = true
	
	local class
	if guid ~= nil and guid ~= "" then
		_, class, _, _, _, _ = GetPlayerInfoByGUID(guid)
	end
	
	if name then
		local color = RAID_CLASS_COLORS[class] or { r = 1, g = 1, b = 1 }
		frame.sender:SetText(("|cFF%2x%2x%2x%s|r"):format(color.r*255, color.g*255, color.b*255, name))
		if frame.text:GetWidth() < frame.sender:GetWidth() then
			frame.text:SetWidth(frame.sender:GetWidth())
		end
	end
end

local function FindFrame(msg)
	for i = 1, WorldFrame:GetNumChildren() do
		local frame = select(i, WorldFrame:GetChildren())
		if not frame:GetName() and not frame.inUse then
			for i = 1, select("#", frame:GetRegions()) do
				local region = select(i, frame:GetRegions())
				if region:GetObjectType() == "FontString" and region:GetText() == msg then
					return frame
				end
			end

		end
	end
end

local f = CreateFrame("Frame")
for e, _ in pairs(events) do f:RegisterEvent(e) end

f:SetScript("OnEvent", function(_, event, ...)
	for e, cvar in pairs(events) do
		if event == e and GetCVarBool(cvar) then
			local msg, sender, _, _, _, _, _, _, _, _, _, guid = ...
			f.elapsed = 0
			f:SetScript("OnUpdate", function(self, elapsed)
				self.elapsed = self.elapsed + elapsed
				local frame = FindFrame(msg)
				if frame or self.elapsed > 0.3 then
					f:SetScript("OnUpdate", nil)
					if frame then UpdateFrame(frame, guid, sender) end
				end
			end)
		end
	end
end)